package org.example.myleet.p989;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    /**
     * 4 ms
     * 简单数学加法逐位进位计算
     */
    public List<Integer> addToArrayForm(int[] A, int K) {
        if (K == 0) {
            return parse(A);
        }
        //先将K转换为数组，确定K的位数，逐位写入数组
        int lg = (int) Math.log10(K);
        int[] kArr = new int[lg+1];
        int kIdx = kArr.length-1, mod = K;
        do {
            kArr[kIdx--] = mod % 10;
        } while((mod /= 10) > 0);
        int[] result = addTwoArr(A, kArr);
        return parse(result);
    }

    private List<Integer> parse(int[] arr) {
        List<Integer> reply = new ArrayList<>(arr.length);
        for (int i : arr) {
            reply.add(i);
        }
        return reply;
    }

    /**
     * 逐位将两个数组加在一起
     */
    private int[] addTwoArr(int[] a, int[] b) {
        int[] longer, shorter;
        if (a.length > b.length) {
            longer = a;
            shorter = b;
        } else {
            longer = b;
            shorter = a;
        }
        int[] result = new int[longer.length+1];
        int shift = 0, resultIdx = result.length-1, shorterIdx = shorter.length-1;
        for (int i=longer.length-1; i>=0; i--) {
            int sum;
            if (shorterIdx >= 0) {
                //逐位相加，数组1+数组2+进位
                sum = longer[i] + shorter[shorterIdx--] + shift;
            } else {
                sum = longer[i] + shift;
            }
            if (sum > 9) {
                //该位计算超过9时需要计算进位
                shift = sum / 10;
                sum %= 10;
            } else {
                shift = 0;
            }
            result[resultIdx--] = sum;
        }
        if (shift != 0) {
            result[resultIdx] = shift;
        }
        if (result[0] == 0) {
            //首位为0时首位丢弃
            return Arrays.copyOfRange(result, 1, result.length);
        }
        return result;
    }
}
